<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 导入组件 -->
      <PageTools>
        <!-- <template #left>  v-slot:left  具名插槽-->
        <template v-slot:left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template v-slot="{row}">
              <img
                v-errorimg="defaultImg"
                :src="row.staffPhoto||defaultImg"
                width="75px"
                height="75px"
                @click="clickShowCodeDialog(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{row}">
              {{ timeOfEntry(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button v-if="checkButton('POINT_USER_LOOK')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button v-if="checkButton('POINT_USER_DELETE')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件    layout="total, sizes, prev, pager, next, jumper"-->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <addEmployee :show-dialog.sync="showDialog" />

      <!-- 生成二维码 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog" width="280px">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <!-- 角色分配组件 -->
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import EmployeeEnum from '@/api/constant/employees'
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import dayjs from 'dayjs'
import addEmployee from './components/add-employee.vue'
import defaultImg from '@/assets/common/03.webp'
import qrcode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  name: 'Employees',
  components: { addEmployee, AssignRole },
  data() {
    return {
      page: 1,
      size: 10,
      total: 0,

      list: [], // 渲染数据

      showDialog: false, // 新增员工的显示隐藏弹窗

      defaultImg, // 默认头像

      showCodeDialog: false, // 二维码弹窗

      showRoleDialog: false, // 点击角色弹窗

      userId: '' // 角色Id
    }
  },
  created() {
    this.GetEmployeeList()
  },
  methods: {
    // 按钮的使用权
    checkButton(type) {
      const arr = this.$store.state.user.userInfo.roles.points
      return arr.includes(type) || true
    },
    // 获取数据
    async GetEmployeeList() {
      const { data: { rows, total }} = await reqGetEmployeeList(this.page, this.size)
      this.total = total
      this.list = rows
    },
    // 分页
    handleCurrentChange(newPage) {
      this.page = newPage
      this.GetEmployeeList()
    },
    // 格式化表格内容 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未入职'
    },
    // 格式化时间日期
    timeOfEntry(time) {
      return dayjs(time).format('YYYY年MM月DD日')
    },
    // 删除
    async delEmployee(id) {
      const ress = await this.$confirm('确定删除吗?', '提示').catch(error => error)
      if (ress !== 'confirm') return
      const res = await reqDelEmployee(id)
      this.$message.success(res.message)
      this.GetEmployeeList()
    },
    // Excel导出员工
    async  handleDownload() {
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      const arr = [] // 外部声明一个数组
      rows.forEach(item => {
        const newArr = [] // 循环里面的这个数组然后push到arr里生成二维数组
        headersArr.forEach(key => { // 循环表头
          const enKey = headersRelations[key]
          if (['timeOfEntry', 'correctionTime'].includes(enKey)) {
            item[enKey] = this.timeOfEntry(item[enKey])
          }
          if (enKey === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(value => value.id === +item[enKey])
            const res = obj ? obj.value : '未知'
            newArr.push(res)
          } else {
            newArr.push(item[enKey]) // 把值push到newArr里
          }
        })
        arr.push(newArr)
      })
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // header表头 必填
          data: arr, // data具体数据 必填
          filename: '信息表', // 导出的文件名称非必填
          autoWidth: true, // 自适应宽度 非必填
          bookType: 'xlsx' // 文件类型 非必填
        })
      })
    },
    // 点击图片生成二维码
    clickShowCodeDialog(data) {
      this.showCodeDialog = true
      this.$nextTick(() => {
        qrcode.toCanvas(this.$refs.myCanvas, data)
      })
    },
    editRole(userId) {
      this.showRoleDialog = true
      this.userId = userId
    }
  }
}
</script>

<style>

</style>
